# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
sendmail = require '../lib/sendmail'

router  = express.Router()
module.exports = router

router.all "/", (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '站内通知', 'href': "/notify"
    res.locals.breadcrumbs.push 'title': '站内留言'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 用户列表
    await client.query \
        "select u.*, count(m.serial) as n_messages from web_users as u
            left join web_messages as m on
                (m.recver = u.uuid or m.sender = u.uuid)
            where u.uuid <> $1 and (m.recver = $1 or m.sender = $1)
            group by u.serial, u.uuid
            order by n_messages", [
            req.session.userinfo.uuid
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.users = result.rows

    # 查询显示内容
    params = []
    sql = "select m.*, u.realname as send_user, u2.realname as recv_user
        from web_messages as m
            left join web_users as u on u.uuid = m.sender
            left join web_users as u2 on u2.uuid = m.recver
        where (m.recver = $1 or m.sender = $1)"
    params.push req.session.userinfo.uuid
    index = 2
    if req.body.start_time and req.body.start_time.length > 0
        sql += " and m.time >= $#{index}"
        index += 1
        params.push req.body.start_time
        res.locals.start_time = req.body.start_time
    if req.body.end_time and req.body.end_time.length > 0
        sql += " and time <= $#{index}"
        index += 1
        params.push req.body.end_time
        res.locals.end_time = req.body.end_time
    if req.body.user
        sql += " and (recver = $#{index} or sender = $#{index})"
        index += 1
        params.push req.body.user
        res.locals.user = req.body.user
    else if req.query.user
        sql += " and (recver = $#{index} or sender = $#{index})"
        index += 1
        params.push req.query.user
        res.locals.user = req.query.user
    sql += " order by time desc"

    await client.query sql, params, defer err, result
    if err then done(client); return next(err)
    done()
    res.render 'message', records: result.rows


router.post '/new', (req, res, next) ->
    for k in ['user', 'message']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "insert into web_messages (sender, recver, message) values (
            $1, $2, $3
        )", [
            req.session.userinfo.uuid,
            req.body.user,
            req.body.message
        ], defer err, result
    if err then done(client); return next(err)

    # 更新系统的通知修改时间，用户下次访问时，将重新查询通知消息
    req.app.set 'notify_modified_time', moment().format('x')

    redirect = if req.body.redirect == 'message' then '/message' else '/notify'

    # 如果用户不在线，则尝试发送一封电子邮件
    await client.query \
        "select * from web_session where sess#>>'{userinfo, uuid}' = $1", [
            req.body.user,
        ], defer err, result
    if err then done(client); return next(err)
    if result.rows.length > 0
        done()
        return res.redirect redirect

    # 查询收信用户信息
    await client.query \
        "select * from web_users where uuid = $1", [
            req.body.user,
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length == 0
        return res.redirect redirect

    user = result.rows[0]
    if not user.email or user.email.length == 0
        return res.redirect redirect

    sendmail
        subject: "来自'#{req.session.userinfo.realname}'的站内留言",
        html: req.body.message,
        to: "\"#{user.realname}\" #{user.email}"

    return res.redirect redirect


router.post '/read', (req, res, next) ->
    res.type('json')
    for k in ['serial', 'recver']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update web_messages set status = 2 where serial = $1 and recver = $2", [
            req.body.serial,
            req.session.userinfo.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    # 更新系统的通知修改时间，用户下次访问时，将重新查询通知消息
    req.app.set 'notify_modified_time', moment().format('x')
    res.json succ: true


router.post '/delete', (req, res, next) ->
    res.type('json')
    for k in ['serial']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "delete from web_messages where serial = $1 and
            (sender = $2 or recver = $2)", [
            req.body.serial,
            req.session.userinfo.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()

    # 更新系统的通知修改时间，用户下次访问时，将重新查询通知消息
    req.app.set 'notify_modified_time', moment().format('x')
    res.json succ: true
